import datetime
import logging
import random
import time
import requests
from cars.models import Car, MthCar
from mgmt.models import Batch, BatchCar
from teacher.models import TeacherInvite, TeacherInviteCar
from visitor.models import VisitorApply, VisitorApplyCar
from ymiot import views as ymiotapi

logger = logging.getLogger("log")


# 教师邀请工单车辆入场状态远程同步
def teacher_carenter_sync_remote():
    print("===开始===教师邀请工单车辆入场状态远程同步===")
    # 教师邀请
    teacher_invite_list = TeacherInvite.objects.filter(status=5)
    print(f"1===审核完成工单数量==={teacher_invite_list.count()}===")
    for teacher_invite in teacher_invite_list:
        print(f"2===开始处理工单==={teacher_invite.__str__()}===")
        teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=teacher_invite)
        print(f"3===工单车辆数量==={teacher_invite_car_list.count()}===")
        if teacher_invite_car_list.count() == 0:
            print(f"4===工单车辆数量为0===结束===")
            continue
        enter_flag = 1
        for teacher_invite_car in teacher_invite_car_list:
            car = teacher_invite_car.car
            plate = car.plate
            print(f"5===开始处理车辆==={plate}===")
            print(f"6===车辆状态==={car.get_status_display()}===")
            if car.status == 3:
                print(f"7===车辆状态为已入场===结束===")
                continue
            start_time = (datetime.datetime.now() - datetime.timedelta(minutes=20)).strftime("%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            # time.sleep(1)
            responseSingle = ymiotapi.get_enter_car_single(plate, start_time, end_time)
            responseSingleMsg = responseSingle["msg"]
            print(f"8===获取入场纪录==={responseSingleMsg}===")
            if responseSingle["code"] != 0:
                print(f"===入场纪录===获取失败===结束===={responseSingleMsg}")
                continue
            print(f"===入场纪录===获取成功==={responseSingleMsg}")
            responseSingleData = responseSingle["data"]
            responseSingleDataCount = responseSingleData["count"]
            if responseSingleDataCount == 0:
                print(f"===入场纪录===无记录===结束====")
                continue
            responseSingleDataLst = responseSingleData["carLst"]
            record = responseSingleDataLst[0]
            car.status = 3
            car.enter_time = record["enterTime"]
            car.enter_gate_name = record["enterGateName"]
            car.save()
            if teacher_invite.isfree == 1:
                print(f"===免费工单======结束====")
            elif not car.visitor_no:
                print(f"===没有访客编号===结束")
            elif teacher_invite.isfree == 0 and car.visitor_no:
                visitor_no = car.visitor_no
                time.sleep(1)
                responseDel = ymiotapi.print(visitor_no, plate)
                print(f"===删除访客==={responseDel['msg']}===")
                car.begin_time = None
                car.end_time = None
                car.visitor_no = None
                car.save()
            if car.status != 3:
                enter_flag = 0
                break
        if enter_flag == 1:
            teacher_invite.status = 7
            teacher_invite.save()
        else:
            continue
    print("===结束===教师邀请工单车辆入场状态远程同步===")


# 教师邀请工单车辆入场状态同步
def teacher_carenter_sync():
    print("===开始===教师邀请工单车辆入场状态同步===")
    # 教师邀请
    teacher_invite_list = TeacherInvite.objects.filter(status=5)
    for teacher_invite in teacher_invite_list:
        print(f"===工单==={teacher_invite.__str__()}===")
        teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=teacher_invite)
        enter_flag = 1
        for teacher_invite_car in teacher_invite_car_list:
            car = teacher_invite_car.car
            if car.status == 3 and teacher_invite.isfree == 0 and car.visitor_no:
                visitor_no = car.visitor_no
                responseDel = ymiotapi.del_visitor_car(visitor_no, car.plate)
                print(f"===删除访客==={responseDel['msg']}===")
                if responseDel["code"] == 0:
                    responseDelMsg = responseDel["msg"]
                    print(responseDelMsg)
                    car.begin_time = None
                    car.end_time = None
                    car.visitor_no = 0
                    car.save()
                else:
                    responseDelMsg = responseDel["msg"]
                    print(responseDelMsg)
            else:
                continue
        if enter_flag == 1:
            teacher_invite.status = 7
            teacher_invite.save()
        else:
            continue
    print("===结束===教师邀请工单车辆入场状态同步===")


# 教师邀请工单车辆出场状态远程同步
def teacher_carout_sync_remote():
    print("===开始===教师邀请工单车辆出场状态远程同步===")
    # 教师邀请
    teacher_invite_list = TeacherInvite.objects.filter(status=7)
    for teacher_invite in teacher_invite_list:
        print(f"===工单==={teacher_invite.__str__()}===")
        teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=teacher_invite)
        out_flag = 1
        for teacher_invite_car in teacher_invite_car_list:
            car = teacher_invite_car.car
            plate = car.plate
            print(f"===车辆==={plate}===")
            start_time = (datetime.datetime.now() - datetime.timedelta(minutes=20)).strftime("%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            time.sleep(1)
            responseSingle = ymiotapi.get_out_car_single(plate, start_time, end_time)
            print(f"===出场纪录==={responseSingle['msg']}===")
            if responseSingle["code"] == 0:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
                responseSingleData = responseSingle["data"]
                responseSingleDataCount = responseSingleData["count"]
                if responseSingleDataCount > 0:
                    responseSingleDataLst = responseSingleData["carLst"]
                    record = responseSingleDataLst[0]
                    car.status = 4
                    car.enter_time = record["enterTime"]
                    car.enter_gate_name = record["enterGateName"]
                    car.save()
                    if teacher_invite.isfree == 0 and car.visitor_no:
                        visitor_no = car.visitor_no
                        time.sleep(1)
                        responseDel = ymiotapi.del_visitor_car(visitor_no, plate)
                        print(f"===删除访客==={responseDel['msg']}===")
                        if responseDel["code"] == 0:
                            responseDelMsg = responseDel["msg"]
                            print(responseDelMsg)
                            car.begin_time = None
                            car.end_time = None
                            car.visitor_no = None
                            car.save()
                        else:
                            responseDelMsg = responseDel["msg"]
                            print(responseDelMsg)
            else:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
            if car.status != 4:
                out_flag = 0
        if out_flag == 1:
            teacher_invite.status = 8
            teacher_invite.save()
        else:
            continue
    print("===结束===教师邀请工单车辆出场状态远程同步===")


# 教师邀请工单车辆出场状态同步
def teacher_carout_sync():
    print("===开始===教师邀请工单车辆出场状态同步===")
    # 教师邀请
    teacher_invite_list = TeacherInvite.objects.filter(status__in=[5, 7])
    for teacher_invite in teacher_invite_list:
        print(f"===工单==={teacher_invite.__str__()}===")
        teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=teacher_invite)
        out_flag = 1
        for teacher_invite_car in teacher_invite_car_list:
            car = teacher_invite_car.car
            if car.status != 4:
                out_flag = 0
        if out_flag == 1:
            teacher_invite.status = 8
            teacher_invite.save()
        else:
            continue
    print("===结束===教师邀请工单车辆出场状态同步===")


# 访客申请工单车辆入场状态远程同步
def visitor_carenter_sync_remote():
    print("===开始===访客申请工单车辆入场状态远程同步===")
    # 访客申请
    visitor_apply_list = VisitorApply.objects.filter(status=5)
    for visitor_apply in visitor_apply_list:
        visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=visitor_apply)
        enter_flag = 1
        for visitor_apply_car in visitor_apply_car_list:
            car = visitor_apply_car.car
            plate = car.plate
            print(f"===车辆==={plate}===")
            start_time = (datetime.datetime.now() - datetime.timedelta(hours=6)).strftime("%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            time.sleep(1)
            responseSingle = ymiotapi.get_enter_car_single(plate, start_time, end_time)
            print(f"===入场纪录==={responseSingle['msg']}===")
            if responseSingle["code"] == 0:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
                responseSingleData = responseSingle["data"]
                responseSingleDataCount = responseSingleData["count"]
                if responseSingleDataCount > 0:
                    responseSingleDataLst = responseSingleData["carLst"]
                    record = responseSingleDataLst[0]
                    car.status = 3
                    car.enter_time = record["enterTime"]
                    car.enter_gate_name = record["enterGateName"]
                    car.save()
                    if visitor_apply.isfree == 0 and car.visitor_no:
                        visitor_no = car.visitor_no
                        time.sleep(1)
                        responseDel = ymiotapi.del_visitor_car(visitor_no, plate)
                        print(f"===删除访客==={responseDel['msg']}===")
                        if responseDel["code"] == 0:
                            responseDelMsg = responseDel["msg"]
                            print(responseDelMsg)
                            car.begin_time = None
                            car.end_time = None
                            car.visitor_no = None
                            car.save()
                        else:
                            responseDelMsg = responseDel["msg"]
                            print(responseDelMsg)
            else:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
            if car.status != 3:
                enter_flag = 0
        if enter_flag == 1:
            visitor_apply.status = 7
            visitor_apply.save()
        else:
            continue
    print("===结束===访客申请工单车辆入场状态远程同步===")


# 访客申请工单车辆入场状态同步
def visitor_carenter_sync():
    print("===开始===访客申请工单车辆入场状态同步===")
    # 访客申请
    visitor_apply_list = VisitorApply.objects.filter(status=5)
    for visitor_apply in visitor_apply_list:
        visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=visitor_apply)
        enter_flag = 1
        for visitor_apply_car in visitor_apply_car_list:
            car = visitor_apply_car.car
            if car.status != 3:
                enter_flag = 0
            else:
                if visitor_apply.isfree == 0 and car.visitor_no:
                    visitor_no = car.visitor_no
                    responseDel = ymiotapi.del_visitor_car(visitor_no, car.plate)
                    print(f"===删除访客==={responseDel['msg']}===")
                    if responseDel["code"] == 0:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
                        car.begin_time = None
                        car.end_time = None
                        car.visitor_no = None
                        car.save()
                        continue
                    else:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
        if enter_flag == 1:
            visitor_apply.status = 7
            visitor_apply.save()
        else:
            continue
    print("===结束===访客申请工单车辆入场状态同步===")


# 访客申请工单车辆出场状态远程同步
def visitor_carout_sync_remote():
    print("===开始===访客申请工单车辆出场状态远程同步===")
    # 访客申请
    visitor_apply_list = VisitorApply.objects.filter(status=7)
    for visitor_apply in visitor_apply_list:
        visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=visitor_apply)
        out_flag = 1
        for visitor_apply_car in visitor_apply_car_list:
            car = visitor_apply_car.car
            plate = car.plate
            print(f"===车辆==={plate}===")
            start_time = (
                    datetime.datetime.now() - datetime.timedelta(minutes=20)
            ).strftime("%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            time.sleep(1)
            responseSingle = ymiotapi.get_out_car_single(plate, start_time, end_time)
            print(f"===出场记录==={responseSingle['msg']}===")
            if responseSingle["code"] == 0:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
                responseSingleData = responseSingle["data"]
                responseSingleDataCount = responseSingleData["count"]
                if responseSingleDataCount > 0:
                    responseSingleDataLst = responseSingleData["carLst"]
                record = responseSingleDataLst[0]
                car.status = 4
                car.out_time = record["outTime"]
                car.out_gate_name = record["outGateName"]
                car.save()
                if visitor_apply.isfree == 0 and car.visitor_no:
                    visitor_no = car.visitor_no
                    time.sleep(1)
                    responseDel = ymiotapi.del_visitor_car(visitor_no, plate)
                    print(f"===删除访客==={responseDel['msg']}===")
                    if responseDel["code"] == 0:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
                        car.begin_time = None
                        car.end_time = None
                        car.visitor_no = None
                        car.save()
                    else:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
            else:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
            if car.status != 4:
                out_flag = 0
        if out_flag == 1:
            visitor_apply.status = 8
            visitor_apply.save()
        else:
            continue
    print("===结束===访客申请工单车辆出场状态远程同步===")


# 访客申请工单车辆出场状态同步
def visitor_carout_sync():
    print("===开始===访客申请工单车辆出场状态同步===")
    # 访客申请
    visitor_apply_list = VisitorApply.objects.filter(status=7)
    for visitor_apply in visitor_apply_list:
        visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=visitor_apply)
        out_flag = 1
        for visitor_apply_car in visitor_apply_car_list:
            car = visitor_apply_car.car
            if car.status != 4:
                out_flag = 0
        if out_flag == 1:
            visitor_apply.status = 8
            visitor_apply.save()
        else:
            continue
    print("===结束===访客申请工单车辆出场状态同步===")


# 批量预约车辆增加访客状态
def batchcar_add_sync():
    print("===开始===批量预约车辆增加访客状态===")
    today = datetime.datetime.today()
    bantch_list = Batch.objects.filter(startdate__lte=today, enddate__gte=today)
    for bantch in bantch_list:
        batch_car_list = BatchCar.objects.filter(batch=bantch)
        for batch_car in batch_car_list:
            time.sleep(5)
            car = batch_car.car
            now = datetime.datetime.now()
            beginTimeTxt = (now + datetime.timedelta(minutes=5)).strftime(
                "%Y-%m-%d %H:%M:%S"
            )
            endTimeTxt = now.replace(hour=23, minute=59, second=59).strftime(
                "%Y-%m-%d %H:%M:%S"
            )
            responseAdd = ymiotapi.add_visitor_car(car.plate, beginTimeTxt, endTimeTxt)
            responseMsg = responseAdd["msg"]
            print(responseMsg)
            if responseAdd["code"] == 0:
                responseData = responseAdd["data"]
                responseData_visitorNo = responseData["visitorNo"]
                responseData_beginTime = responseData["beginTime"]
                responseData_endTime = responseData["endTime"]
                car.status = 2
                car.visitor_no = responseData_visitorNo
                car.begin_time = responseData_beginTime
                car.end_time = responseData_endTime
                car.save()
    print("===结束===批量预约车辆访客状态部署===")


# 批量预约车辆解除访客状态
def batchcar_del_sync():
    print("===开始===批量预约车辆访客状态部署===")
    today = datetime.datetime.today()
    bantch_list = Batch.objects.filter(startdate__lte=today, enddate__gte=today)
    for bantch in bantch_list:
        if bantch.isfree == 1:
            continue
        batch_car_list = BatchCar.objects.filter(batch=bantch)
        for batch_car in batch_car_list:
            car = batch_car.car
            plate = car.plate
            if car.status != 2:
                continue
            print(f"===车辆==={car.plate}===")
            start_time = (
                    datetime.datetime.now() - datetime.timedelta(minutes=20)
            ).strftime("%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            responseSingle = ymiotapi.get_enter_car_single(plate, start_time, end_time)
            print(f"===入场纪录==={responseSingle['msg']}===")
            if responseSingle["code"] == 0:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
                responseSingleData = responseSingle["data"]
                responseSingleDataCount = responseSingleData["count"]
                if responseSingleDataCount > 0:
                    responseSingleDataLst = responseSingleData["carLst"]
                    record = responseSingleDataLst[0]
                    car.status = 3
                    car.enter_time = record["enterTime"]
                    car.enter_gate_name = record["enterGateName"]
                    car.save()
                    visitor_no = car.visitor_no
                    if visitor_no and bantch.isfree == 0:
                        responseDel = ymiotapi.del_visitor_car(visitor_no, plate)
                    print(f"===删除访客==={responseDel['msg']}===")
                    if responseDel["code"] == 0:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
                        car.begin_time = None
                        car.end_time = None
                        car.visitor_no = None
                        car.save()
                    else:
                        responseDelMsg = responseDel["msg"]
                        print(responseDelMsg)
            else:
                responseSingleMsg = responseSingle["msg"]
                print(responseSingleMsg)
    print("===结束===批量预约车辆访客状态部署===")


def syncCarEnter():
    car_list = Car.objects.filter(status=2)
    for car in car_list:
        plate = car.plate
        print(f"===车牌==={plate}===")
        start_time = (datetime.datetime.now() - datetime.timedelta(hours=12)).strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        responseSingle = ymiotapi.get_enter_car_single(plate, start_time, end_time)
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        if responseSingle["code"] == 0:
            responseSingleMsg = responseSingle["msg"]
            print(responseSingleMsg)
            responseSingleData = responseSingle["data"]
            responseSingleDataCount = responseSingleData["count"]
            if responseSingleDataCount > 0:
                responseSingleDataLst = responseSingleData["carLst"]
                record = responseSingleDataLst[0]
                car.status = 3
                car.enter_time = record["enterTime"]
                car.enter_gate_name = record["enterGateName"]
                car.save()
    visitor_carenter_sync()
    teacher_carenter_sync()


def syncSingleCarEnter(plate):
    car = Car.objects.get(plate=plate)
    start_time = (datetime.datetime.now() - datetime.timedelta(hours=24)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    responseSingle = ymiotapi.get_enter_car_single(plate, start_time, end_time)
    responseSingleMsg = responseSingle["msg"]
    print(responseSingleMsg)
    if responseSingle["code"] == 0:
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        responseSingleData = responseSingle["data"]
        responseSingleDataCount = responseSingleData["count"]
        if responseSingleDataCount > 0:
            responseSingleDataLst = responseSingleData["carLst"]
            record = responseSingleDataLst[0]
            car.status = 3
            car.enter_time = record["enterTime"]
            car.enter_gate_name = record["enterGateName"]
            car.save()
    visitor_carenter_sync()
    teacher_carenter_sync()


def syncCarOut():
    car_list = Car.objects.filter(status=3).filter()
    for car in car_list:
        plate = car.plate
        print(f"===车牌==={plate}===")
        start_time = (datetime.datetime.now() - datetime.timedelta(hours=23)).strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        responseSingle = ymiotapi.get_out_car_single(plate, start_time, end_time)
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        if responseSingle["code"] == 0:
            responseSingleMsg = responseSingle["msg"]
            print(responseSingleMsg)
            responseSingleData = responseSingle["data"]
            responseSingleDataCount = responseSingleData["count"]
            if responseSingleDataCount > 0:
                responseSingleDataLst = responseSingleData["carLst"]
                record = responseSingleDataLst[0]
                car.status = 4
                car.out_time = record["outTime"]
                car.out_gate_name = record["outGateName"]
                car.save()
    visitor_carout_sync()
    teacher_carout_sync()


def syncSingleCarOut(plate):
    car = Car.objects.get(plate=plate)
    start_time = (datetime.datetime.now() - datetime.timedelta(hours=24)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    responseSingle = ymiotapi.get_out_car_single(plate, start_time, end_time)
    responseSingleMsg = responseSingle["msg"]
    print(responseSingleMsg)
    if responseSingle["code"] == 0:
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        responseSingleData = responseSingle["data"]
        responseSingleDataCount = responseSingleData["count"]
        if responseSingleDataCount > 0:
            responseSingleDataLst = responseSingleData["carLst"]
            record = responseSingleDataLst[0]
            car.status = 4
            car.out_time = record["outTime"]
            car.out_gate_name = record["outGateName"]
            car.save()
    visitor_carout_sync()
    teacher_carout_sync()


def syncLongCarOut():
    # 全部场内
    car_list = Car.objects.filter(status=3).exclude(enter_time=None)
    # 长期未出场车辆
    long_car_list = []
    for car in car_list:
        plate = car.plate
        print(f"===车牌==={plate}===")
        enter_time = datetime.datetime.strptime(car.enter_time, "%Y-%m-%d %H:%M:%S")
        duration = datetime.datetime.now() - enter_time
        hours = (duration.seconds / 3600) + duration.days * 24
        print(f"===时长==={int(hours)}小时===")
        if hours > 12:
            long_car_item = {}
            long_car_item["car"] = car
            long_car_item["duration"] = int(hours)
            long_car_list.append(long_car_item)
    print(f"===全部场内==={car_list.count()}===")
    print(f"===12小时以上==={len(long_car_list)}===")
    for long_car in long_car_list:
        car = long_car["car"]
        plate = car.plate
        print(f"===车牌==={plate}===")
        print(f"===duration==={long_car['duration']}===")
        enter_time = car.enter_time
        print(f"===enter_time==={enter_time}===")
        end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"===end_time==={end_time}===")
        responseSingle = ymiotapi.get_out_car_single(plate, enter_time, end_time)
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        responseSingleMsg = responseSingle["msg"]
        print(responseSingleMsg)
        responseSingleData = responseSingle["data"]
        responseSingleDataCount = responseSingleData["count"]
        if responseSingleDataCount > 0:
            responseSingleDataLst = responseSingleData["carLst"]
            record = responseSingleDataLst[0]
            car.status = 4
            car.out_time = record["outTime"]
            car.out_gate_name = record["outGateName"]
            car.save()
        print(f"===完成==={car}===")


# import datetime
# import logging
# from cars.models import Car
# from mgmt.models import Batch, BatchCar
# from teacher.models import TeacherInvite, TeacherInviteCar
# from visitor.models import VisitorApply, VisitorApplyCar
# from ymiot import views as ymiotapi
# car = Car.objects.get(plate="青A56F79")
# plate = car.plate
# start_time = (datetime.datetime.now() - datetime.timedelta(hours=24)).strftime("%Y-%m-%d %H:%M:%S")
# end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# responseSingle = ymiotapi.get_out_car_single(plate,start_time,end_time)
# responseSingleMsg = responseSingle["msg"]
# print(responseSingleMsg)
# if responseSingle["code"] == 0:
#     responseSingleMsg = responseSingle["msg"]
#     print(responseSingleMsg)
#     responseSingleData = responseSingle["data"]
#     responseSingleDataCount = responseSingleData["count"]
#     if responseSingleDataCount > 0:
#         responseSingleDataLst = responseSingleData["carLst"]
#         record = responseSingleDataLst[0]
#         car.status = 4
#         car.out_time = record['outTime']
#         car.out_gate_name = record['outGateName']
#         car.save()

# from cars import tasks
# tasks.visitor_carout_sync()


# # 访客申请
# visitor_apply_list = VisitorApply.objects.filter(status=7)
# for visitor_apply in visitor_apply_list:
#     visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=visitor_apply)
#     for visitor_apply_car in visitor_apply_car_list:
#         car = visitor_apply_car.car
#         if car.status != 3:
#             enter_flag = 0
#         else:
#             if visitor_apply.isfree == 0:
#                 visitor_no = car.visitor_no
#                 if visitor_no:
#                     responseDel = ymiotapi.print(visitor_no, car.plate)
#                     print(f"===删除访客==={responseDel["msg"]}===")
#                     if responseDel['code'] == 0:
#                         responseDelMsg = responseDel["msg"]
#                         print(responseDelMsg)
#                         car.begin_time = None
#                         car.end_time = None
#                         car.save()
#                         continue
#                     else:
#                         responseDelMsg = responseDel["msg"]
#                         print(responseDelMsg)


def SyncMthCar():
    # 接口名称
    now = datetime.datetime.now()
    apiname = "月租车辆同步"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 查看库中车辆是否在系统中
    logger.info(f"接口>>>{apiname}>>>开始处理免费车辆")
    freeCarLst = MthCar.objects.filter(carTypeNo=3656, updated__lt=now)
    for freeCar in freeCarLst:
        carNo = freeCar.carNo
        print(f"===处理免费车==={carNo}===")
        responseSearch = ymiotapi.search_mthcar(carNo)
        print(f"===查询免费车==={responseSearch['msg']}===")
        if responseSearch["code"] == 0:
            responseSearchData = responseSearch["data"]
            carDet = responseSearchData["carDet"]
            freeCar.beginTime = carDet["beginTime"]
            freeCar.endTime = carDet["endTime"]
            freeCar.iusseTime = carDet["iusseTime"]
            freeCar.userName = carDet["userName"]
            freeCar.phone = carDet["phone"]
            freeCar.homeAddress = carDet["homeAddress"]
            freeCar.save()
            # 更新一波数据
            continue
        else:
            print("没找到记录")
        endTime = freeCar.endTime
        endTime = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
        if endTime < datetime.datetime.now():
            print("免费车已过期,不管了")
        else:
            print("月租车未过期,可能丢了")
            print("开始续租")
            # 1 处理人员
            responsePerson = ymiotapi.add_person(
                "3656", freeCar.userName, freeCar.homeAddress, str(freeCar.phone)
            )
            print(f"===处理人员==={responsePerson['msg']}===")
            if responseSearch["code"] == 0:
                responsePersonData = responsePerson["data"]
                userNo = responsePersonData["userNo"]
                freeCar.userNo = userNo
                freeCar.save()
            else:
                continue
            # 2 处理车辆
            responseAdd = ymiotapi.add_mthcar(carNo, userNo)
            print(f"===处理车辆==={responseAdd['msg']}===")
            if responseAdd["code"] == 0:
                responseAddData = responseAdd["data"]
            else:
                continue
            # 3 车辆续期
            responseCharge = ymiotapi.charge_mthcar(
                carNo, freeCar.beginTime, freeCar.endTime
            )
            print(f"===车辆续期==={responseCharge['msg']}===")
            if responseCharge["code"] == 0:
                responseChargeData = responseCharge["data"]
                freeCar.beginTime = responseChargeData["beginTime"]
                freeCar.endTime = responseChargeData["endTime"]
                freeCar.save()
            else:
                continue


# 查询系统内部的全部月租车辆车辆
def downLoadMthCar():
    # 接口名称
    now = datetime.datetime.now()
    apiname = "月租车辆同步"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 月租车辆获取
    for i in range(100):
        print("第" + str(i + 1) + "页")
        logger.info("第" + str(i + 1) + "页")
        page = i
        rand = str(random.uniform(0, 9))
        rawdata = {}
        rawdata["appid"] = ymiotapi.APPID
        rawdata["rand"] = rand
        rawdata["version"] = "v1.1"
        rawdata["parkKey"] = ymiotapi.PARKKEY
        rawdata["indexId"] = str(page)
        rawdata["size"] = "100"
        signeddata = ymiotapi.signdata(rawdata)
        url = ymiotapi.HOST + "/Inquire/GetMthCarInfo"
        response = requests.post(url, json=signeddata)
        response_json = response.json()
        response_code = response_json["code"]
        if response_code == 1:
            carList = response_json["data"]
            if len(carList) == 0:
                print("没了，结束了")
                break
            for car in carList:
                print("car")
                print(car)
                carNo = car["carNo"]
                try:
                    mthCar = MthCar.objects.get(carNo=carNo)
                except MthCar.DoesNotExist:
                    mthCar = MthCar()
                mthCar.carNo = car["carNo"]
                mthCar.carTypeNo = car["carTypeNo"]
                mthCar.beginTime = car["beginTime"]
                mthCar.endTime = car["endTime"]
                mthCar.iusseTime = car["iusseTime"]
                mthCar.userName = car["userName"]
                mthCar.phone = car["phone"]
                mthCar.homeAddress = car["homeAddress"]
                mthCar.save()
        else:
            continue


def updateMthCar():
    now = datetime.datetime.now()
    apiname = "丢失车辆同步"
    # 找到没了的车
    logger.info(f"接口>>>{apiname}>>>开始处理免费车辆")
    errCarLst = MthCar.objects.exclude(updated__year=now.year, updated__month=now.month, updated__day=now.day)
    for errCar in errCarLst:
        endTime = errCar.endTime
        endTime = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
        if endTime < datetime.datetime.now():
            print("月租车已过期")
            continue
        else:
            print("月租车未过期")
            print("开始续租")
            carNo = errCar.carNo
            print(carNo)
            info_rand = str(random.uniform(0, 9))
            info_rawdata = {}
            info_rawdata["appid"] = ymiotapi.APPID
            info_rawdata["rand"] = info_rand
            info_rawdata["version"] = "v1.0"
            info_rawdata["parkKey"] = ymiotapi.PARKKEY
            info_rawdata["carNo"] = carNo
            info_signeddata = ymiotapi.signdata(info_rawdata)
            info_url = ymiotapi.HOST + "/Inquire/GetMthCarInfo"
            try:
                info_response = requests.post(info_url, json=info_signeddata)
                info_response_json = info_response.json()
            except Exception as e:
                print("接口失败")
                print(e)
                continue
            info_response_code = info_response_json["code"]
            if info_response_code == 1:
                print("月租车存在")
                info_response_data = info_response_json["data"]
                errCar.carNo = info_response_data["carNo"]
                errCar.carTypeNo = info_response_data["carTypeNo"]
                errCar.beginTime = info_response_data["beginTime"]
                errCar.endTime = info_response_data["endTime"]
                errCar.iusseTime = info_response_data["iusseTime"]
                errCar.userName = info_response_data["userName"]
                errCar.phone = info_response_data["phone"]
                errCar.homeAddress = info_response_data["homeAddress"]
                errCar.save()
            else:
                add_response = ymiotapi.add_mthcar(carNo, errCar.userNo)
                add_response_code = add_response["code"]
                if add_response_code == 1:
                    print("月租车新增成功")
                    charge_response = ymiotapi.charge_mthcar(
                        carNo, errCar.beginTime, errCar.endTime
                    )
                    charge_response_code = charge_response["code"]
                    if charge_response_code == 0:
                        print("续费成功")
                    else:
                        print("续费失败")
                        continue
                else:
                    addP_response = ymiotapi.add_person(
                        errCar.carTypeNo,
                        errCar.userName,
                        errCar.homeAddress,
                        errCar.phone,
                    )
                    addP_response_code = addP_response["code"]
                    if addP_response_code == 0:
                        print("新增人员成功")
                        userNo = addP_response["data"]["userNo"]
                        errCar.userNo = userNo
                        errCar.save()
                        addPC = ymiotapi.add_mthcar(carNo, userNo)
                        addPC_code = addPC["code"]
                        if addPC_code != 0:
                            print("新增月租车失败")
                        else:
                            addPCC = ymiotapi.charge_mthcar(
                                carNo, errCar.beginTime, errCar.endTime
                            )
                            addPCC_code = addPCC["code"]
                            if addPCC_code == 0:
                                print("续费成功")
                            else:
                                print("续费失败")
                    else:
                        print("新增人员失败")



def removeOldTeacherInvite():
    print("===处理过期教师邀约===开始===")
    # 获取今日日期
    today = datetime.datetime.now().today().date()
    print(f"===获取今日日期==={today.strftime('%Y-%m-%d')}===")
    # 获取今日0点的时间
    teacherInviteList = TeacherInvite.objects.exclude(status__in=[6, 8, 9, 10]).filter(when__lt=today)
    print(f"===未完结邀约数量==={teacherInviteList.count()}===")
    for teacherInvite in teacherInviteList:
        print(f"===邀约==={teacherInvite.__str__()}===开始处理===")
        print(f"===邀约状态==={teacherInvite.get_status_display()}===")
        print(f"===邀约日期==={teacherInvite.when}===")
        print(f"===邀约免费==={teacherInvite.isfree}===")
        # 开始处理审核完成的
        inviteCarList = TeacherInviteCar.objects.filter(invite=teacherInvite)
        print(f"===邀约车辆===开始处理==={inviteCarList.count()}")
        for inviteCar in inviteCarList:
            car = inviteCar.car
            plate = car.plate
            print(f"===邀约车辆==={plate}===开始处理===")
            print(f"===邀约车辆状态==={car.get_status_display()}===")
            if car.visitor_no:
                print("===邀约车辆===拥有访客状态===")
                print(f"===邀约车辆===删除访客===开始===")
                del_response = ymiotapi.del_visitor_car(car.visitor_no, plate)
                print(f"===邀约车辆===删除访客==={del_response}")
                car.visitor_no = None
                car.begin_time = None
                car.end_time = None
                car.status = 4
                car.save()
            else:
                print("===邀约车辆===无访客状态===")
                car.visitor_no = None
                car.begin_time = None
                car.end_time = None
                car.status = 4
                car.save()
        print(f"===邀约车辆===结束处理===")
        if teacherInvite.status == 0 or teacherInvite.status == 1 or teacherInvite.status == 2:
            print(f"===邀约还在审核中===过期")
            teacherInvite.status = 9
        else:
            print(f"===邀约还审核完成===完成")
            teacherInvite.status = 8
        teacherInvite.save()
        print(f"===更改邀约状态==={teacherInvite.get_status_display()}===结束===")
    print("===处理过期教师邀约===结束===")


def removeOldVisitorApply():
    print("===处理过期访客申请===开始===")
    # 获取今日日期
    today = datetime.datetime.now().today().date()
    print(f"===获取今日日期==={today.strftime('%Y-%m-%d')}===")
    # 获取今日0点的时间
    visitorApplyList = VisitorApply.objects.exclude(status__in=[6, 8, 9, 10]).filter(when__lt=today)
    print(f"===未完结申请数量==={visitorApplyList.count()}===")
    for visitorApply in visitorApplyList:
        print(f"===申请==={visitorApply.__str__()}===开始处理===")
        print(f"===申请状态==={visitorApply.get_status_display()}===")
        print(f"===申请日期==={visitorApply.when}===")
        print(f"===申请免费==={visitorApply.isfree}===")
        # 开始处理审核完成的
        applyCarList = VisitorApplyCar.objects.filter(apply=visitorApply)
        print(f"===申请车辆===开始处理==={applyCarList.count()}")
        for applyCar in applyCarList:
            car = applyCar.car
            plate = car.plate
            print(f"===申请车辆==={plate}===开始处理===")
            print(f"===申请车辆状态==={car.get_status_display()}===")
            if car.visitor_no:
                print("===申请车辆===拥有访客状态===")
                print(f"===申请车辆===删除访客===开始===")
                del_response = ymiotapi.del_visitor_car(car.visitor_no, plate)
                print(f"===申请车辆===删除访客==={del_response}")
                car.visitor_no = None
                car.begin_time = None
                car.end_time = None
                car.status = 4
                car.save()
            else:
                print("===申请车辆===无访客状态===")
                car.visitor_no = None
                car.begin_time = None
                car.end_time = None
                car.status = 4
                car.save()
        print(f"===申请车辆===结束处理===")
        if visitorApply.status == 0 or visitorApply.status == 1 or visitorApply.status == 2:
            print(f"===申请还在审核中===过期")
            visitorApply.status = 9
        else:
            print(f"===申请审核完成===完成")
            visitorApply.status = 8
        visitorApply.save()
        print(f"===更改申请状态==={visitorApply.get_status_display()}===结束===")
    print("===处理过期访客申请===结束===")

# # 删除过期待入访客车辆
# print("===删除过期待入访客车辆===开始===")
# dt = datetime.datetime(2024, 6, 15, 0, 0, 0)
# print(f"===获取今日日期==={dt.strftime('%Y-%m-%d')}===")
# oldCarList = Car.objects.filter(end_time__lt=dt).exclude(visitor_no=None)
# # oldCarList = Car.objects.filter(end_time__lt=dt).exclude(visitor_no=None)
# # oldCarList = Car.objects.filter(status=2).filter(end_time__lt=dt).exclude(visitor_no=None)
# # oldCarList = Car.objects.filter(status=2).filter(end_time=None)
# print(f"===过期待入车辆数量==={oldCarList.count()}===")
# for oldCar in oldCarList:
#     # oldCar=oldCarList[0]
#     print(f"===车辆==={oldCar.plate}===")
#     print(f"===车辆状态==={oldCar.get_status_display()}===")
#     print(f"===visitor_no==={oldCar.visitor_no}===")
#     print(f"===begin_time==={oldCar.begin_time}===")
#     print(f"===end_time==={oldCar.end_time}===")
#     if not oldCar.visitor_no:
#         print(f"===无访客状态===结束===")
#     else:
#         responseDel = ymiotapi.del_visitor_car(oldCar.visitor_no, oldCar.plate)
#         print(f"===删除访客==={responseDel['msg']}===")
#     oldCar.status = 4
#     oldCar.begin_time = None
#     oldCar.end_time = None
#     oldCar.visitor_no = None
#     oldCar.save()

# 更改待入车辆状态
# dt = datetime.datetime(2024, 6, 15, 0, 0, 0)
# oldCarList = Car.objects.filter(status=1,visitor_no=None,updated__lt=dt)
# for oldCar in oldCarList:
#     oldCar.status = 4
#     oldCar.begin_time = None
#     oldCar.end_time = None
#     oldCar.visitor_no = None
#     oldCar.save()

# oldCar = Car.objects.get(plate='青A5N568')
# print(oldCar.plate)
# print(oldCar.end_time)
# print(oldCar.visitor_no)
# visitor_no = oldCar.visitor_no
# plate = oldCar.plate
# print("plate",plate)
# responseDel = ymiotapi.del_visitor_car(visitor_no, plate)
# print(f"===删除访客==={responseDel["msg"]}===")
# if responseDel["code"] == 0:
#     responseDelMsg = responseDel["msg"]
#     print(responseDelMsg)
#     oldCar.status = 4
#     oldCar.begin_time = None
#     oldCar.end_time = None
#     oldCar.visitor_no = None
#     oldCar.save()
# else:
#     responseDelMsg = responseDel["msg"]
#     print(responseDelMsg)
